package com.kstudio.ksnapshot.klist;

import java.io.File;
import java.util.ArrayList;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.kstudio.ksnapshot.KSnapShotAsync;
import com.kstudio.ksnapshot.KSnapShotAsync.KSnapShotAsyncListener;
import com.kstudio.ksnapshot.KSnapshot;
import com.kstudio.ksnapshot.KUtil;
import com.kstudio.ksnapshot.R;
import com.kstudio.ksnapshot.kedit.KEditActivity;
import com.kstudio.ksnapshot.kimage.KImageActivity;

public class KListActivity extends Activity implements KSnapShotAsyncListener {
    KUtil log = new KUtil("KListActivity");

    private KSnapshot kApplication;
    private Context kContext;

    private ListView kList;
    private ArrayList<KListFileData> kFileList;
    private KListAdapter kAdapter;

    private KSnapShotAsync kSnapShotAsync = null;

    private String kCurrentpath;
    private int kIconWidth;
    private int kIconHeight;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        log.i("***************** onCreate *****************");

        super.onCreate(savedInstanceState);
        setContentView(R.layout.klist_activity);

        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);

        init();
    }

    @Override
    protected void onResume() {
        log.i("***************** onResume *****************");

        super.onResume();

        kSnapShotAsync.KResume();
    }

    @Override
    protected void onPause() {
        log.i("***************** onPause *****************");

        kSnapShotAsync.KPause();

        super.onPause();
    }

    @Override
    protected void onStop() {
        log.i("***************** onStop *****************");

        super.onStop();
    }

    @Override
    protected void onDestroy() {
        log.i("***************** onDestroy *****************");

        kSnapShotAsync.KStop();

        super.onDestroy();
    }

    /* Menu */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_klist, menu);

        return true;
    }

    /* Event */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            case android.R.id.home:
                if(kCurrentpath.compareTo(Environment.getExternalStorageDirectory().getPath()) == 0) {
                    finish();
                } else {
                    char separatorChar = System.getProperty("file.separator", "/").charAt(0);
                    int separatorIndex = kCurrentpath.lastIndexOf(String.valueOf(separatorChar));

                    kApplication.setCurrentPath(kCurrentpath.substring(0, separatorIndex));
                    kCurrentpath = kApplication.getCurrentPath();

                    KUpdateFileList(kCurrentpath);
                    kAdapter.notifyDataSetChanged();
                }
            return true;

            case R.id.menu_repository :
                Intent intent = new Intent(kContext, KImageActivity.class);
                startActivity(intent);
            return true;

        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        // TODO Auto-generated method stub
        super.onSaveInstanceState(outState);
    }

    private class KOnItemClickListenr implements OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> adapterview, View view, int i, long l) {
            log.i("onItemClick %d",i);
            KListFileData fileData = (KListFileData) adapterview.getItemAtPosition(i);

            if(fileData.getAttribute() == KListFileData.FOLDER) {
                kCurrentpath = fileData.getPath();
                kApplication.setCurrentPath(kCurrentpath);

                KUpdateFileList(kCurrentpath);
                kAdapter.notifyDataSetChanged();
            } else if(fileData.getAttribute() == KListFileData.VIDEO) {
                Intent intent = new Intent(kContext, KEditActivity.class);
                intent.putExtra("path", fileData.getPath());
                startActivity(intent);
            }
        }
    }

    /* Listener */
    @Override
    public void OnProgressUpdate() {
        kAdapter.notifyDataSetChanged();
    }

    /* private */
    private void init() {
        kApplication = (KSnapshot) getApplicationContext();
        kCurrentpath = kApplication.getCurrentPath();

        kContext = this;
        kSnapShotAsync = new KSnapShotAsync(this);
        kFileList = new ArrayList<KListFileData>();
        kAdapter = new KListAdapter(this, kFileList);

        kList = (ListView)findViewById(R.id.klist);
        Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.klist_file);
        kIconWidth = b.getWidth();
        kIconHeight = b.getHeight();
        b.recycle();

        KUpdateFileList(kCurrentpath);
        kList.setAdapter(kAdapter);
        kList.setOnItemClickListener(new KOnItemClickListenr());
    }

    private void KUpdateFileList(String currentpath) {
        File[] files = new File(currentpath).listFiles();

        ArrayList<File> folderList = new ArrayList<File>();
        ArrayList<File> fileList = new ArrayList<File>();

        kFileList.clear();

        for(File file: files) {
            if(file.isDirectory()) {
                folderList.add(file);
            } else {
                fileList.add(file);
            }
        }

        for(int i = 0; i < folderList.size(); i++) {
            kFileList.add(new KListFileData(folderList.get(i).getPath(), KListFileData.FOLDER));
        }

        String[] VideoExtiontion = {"3GP","3gp","MP4","mp4","MKV","mkv"};
        String[] PictureExtiontion = {"PNG","png","JPG","jpg","BMP","bmp"};
        int fileType = 0;
        String name;
        String extention;
        int extentionIndex;

        for(int i = 0; i < fileList.size(); i++) {
            fileType = KListFileData.FILE;

            name = fileList.get(i).getPath();
            extentionIndex = name.lastIndexOf(String.valueOf('.'));
            if(extentionIndex > 0) {
                extention = name.substring(extentionIndex + 1);
                for(String ex : VideoExtiontion) {
                    if(extention.equals(ex)) {
                        fileType = KListFileData.VIDEO;
                        break;
                    }
                }
                for(String ex : PictureExtiontion) {
                    if(extention.equals(ex)) {
                        fileType = KListFileData.PICTURE;
                        break;
                    }
                }
            }
            kFileList.add(new KListFileData(fileList.get(i).getPath(), fileType));
        }

        kSnapShotAsync.KStart(KSnapShotAsync.SNAPSHOT_GET_LIST_THUMBNAIL,
                             (ArrayList<?>) kFileList, kIconWidth, kIconHeight);
    }
}
